package com.lifeonwalden.game.mindustry.entity;

import com.lifeonwalden.game.mindustry.constant.Gate;
import com.lifeonwalden.game.mindustry.constant.League;
import com.lifeonwalden.game.mindustry.constant.PorterType;
import com.lifeonwalden.game.mindustry.constant.ResourceType;
import com.lifeonwalden.game.mindustry.model.DrillProperty;

import java.util.Optional;

public class Drill extends StaticEntity {
    public float productivity;
    public ResourceType resourceType;
    private StaticEntity[] linkedUnit = new StaticEntity[4];
    public long timeCounter = 0;

    public Drill() {
        this.league = League.Pathfinder;
        this.hp = this.type.maxHp;
    }

    @Override
    public void doJobBefore() {
        long now = System.currentTimeMillis();
        if (now > timeCounter) {
            if (count < ((DrillProperty) this.type.property).capacity) {
                count += productivity;
            }
            timeCounter = now + ((DrillProperty) this.type.property.property()).speed;
        }
    }

    @Override
    public Optional<ResourceType> take() {
        if (count > 1) {
            count -= 1;

            return Optional.of(this.resourceType);
        }

        return Optional.empty();
    }

    @Override
    public void join(StaticEntity unit, Gate at) {
        this.linkedUnit[at.ordinal()] = unit;
    }

    @Override
    public void unjoin(Gate at) {
        this.linkedUnit[at.ordinal()] = null;
    }

    @Override
    public PorterType porterAt(Gate gate) {
        return PorterType.EXPORTER;
    }

    @Override
    public void destroy() {
        for (int i = 0; i < linkedUnit.length; i++) {
            if (null != linkedUnit[i]) {
                linkedUnit[i].unjoin(Gate.fromOrdinal(i).linkedGate());
            }
        }
    }

    @Override
    public Surface copy(boolean deep) {
        Drill newOne = (Drill) super.copy(deep);
        if (!deep) {
            newOne.resourceType = null;
            newOne.linkedUnit = new StaticEntity[4];
        }
        return newOne;
    }
}
